package com.naizhuai.ui.mianbusiness.action;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.naizhuai.R;
import com.naizhuai.network.exception.ApiException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.entity.CommonLabel;
import com.naizhuai.ui.adapter.business.ActionAddImageAdapterHolder;
import com.naizhuai.ui.adapter.business.ActionBrightPointImageAdapterHolder;
import com.naizhuai.ui.adapter.business.ActionImageBrightPointProcessAdapterHolder;
import com.naizhuai.ui.entity.SimpleKeyValueBean;
import com.naizhuai.ui.entity.mainbusiness.ActionBaseBean;
import com.naizhuai.ui.entity.mainbusiness.ActionCompareDataBean;
import com.naizhuai.ui.entity.mainbusiness.ActionEditContractActivityBean;
import com.naizhuai.ui.entity.mainbusiness.ActionSelectedProcessImageDetails;
import com.naizhuai.ui.entity.mainbusiness.CompareImageBean;
import com.naizhuai.ui.entity.mainbusiness.SubmitExamineBean;
import com.naizhuai.ui.loopviewpager.AutoLoopViewPager;
import com.naizhuai.ui.mianbusiness.action.presenter.ActionManageApiStoreIml;
import com.naizhuai.ui.task.TaskActionApiIml;
import com.naizhuai.ui.viewpagerindicator.CirclePageIndicator;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.ErrorViewCreateUtils;
import com.naizhuai.util.ImageUtils;
import com.naizhuai.util.IntentUtils;
import com.naizhuai.util.ListUtils;
import com.naizhuai.util.MathUtils;
import com.naizhuai.util.NaizhuAILog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observer;
import rx.Subscription;
import rx.functions.Action1;
import rx.subjects.PublishSubject;

/**
 * 行为审批界面
 */
public class ActionExamineActivity extends BaseActivity implements View.OnClickListener, ActionBrightPointImageAdapterHolder.OnItemClickListener {
    private static final String TAG = "ActionExamineActivity";

//    private static final String VIRTUAL_ID = "153";

    private String actionId;

    //行为标题
    @BindView(R.id.action_name)
    TextView actionName;

    //展示合成图片内容
    @BindView(R.id.edit_pager)
    AutoLoopViewPager editPager;
    @BindView(R.id.pager_indicator)
    CirclePageIndicator magicIndicator;
    private List<CompareImageBean> mergeImageList;
    private EditContractPagerAdapter targetAdapter;

    //分析
    @BindView(R.id.analysis_txt)
    RecyclerView analysisRecy;
    List<String> analysisList;
    private ActionImageBrightPointProcessAdapterHolder analysisAdapter;
    @BindView(R.id.analysis_layout)
    CardView analysisLayout;

    //过程数据以及图片
    @BindView(R.id.process_lines_txt)
    RecyclerView recyclerProTxt;
    @BindView(R.id.process_images)
    RecyclerView recyclerProImg;
    private List<String> processStr;
    private List<String> processImg;
    @BindView(R.id.process_details_layout)
    CardView processLayout;

    private ActionSelectedProcessImageDetails imageDetails;
    //过程图片+过程描述的adapter
    private ActionBrightPointImageAdapterHolder imageContentAdapter;
    private ActionImageBrightPointProcessAdapterHolder detailsAdapter;

    //心得
    @BindView(R.id.experience_layout)
    CardView experienceCard;
    @BindView(R.id.action_experience)
    TextView actionExperience;

    //標簽數據以及標簽選擇
    @BindView(R.id.label1)
    TextView label1;
    @BindView(R.id.label2)
    TextView label2;
    @BindView(R.id.label3)
    TextView label3;
    @BindView(R.id.label4)
    TextView label4;
    @BindView(R.id.label5)
    TextView label5;
    @BindView(R.id.label6)
    TextView label6;

    private TextView[] labels;

    private List<CommonLabel> selectorLabel;

    private String labelsRoot_5;

    //数据展示
    @BindView(R.id.compare_data_card)
    CardView compareDataCard;
    @BindView(R.id.before_data)
    TextView preData;
    @BindView(R.id.after_data)
    TextView aftData;
    @BindView(R.id.improve_ratio)
    TextView proRatio;
    @BindView(R.id.improve_money)
    TextView proMoney;
    @BindView(R.id.b_value_count_type)
    TextView beforeValueType;
    @BindView(R.id.a_value_count_type)
    TextView afterValueType;

    @BindView(R.id.b_value_layout)
    LinearLayout bValueLayout;
    @BindView(R.id.a_value_layout)
    LinearLayout aValueLayout;

    //行为行动值
    @BindView(R.id.action_point)
    TextView actionPoint;

    //领导的行为评分
    private int selectPoint = 0;
    @BindView(R.id.star_wide_0)
    ImageView star0;
    @BindView(R.id.star_wide_1)
    ImageView star1;
    @BindView(R.id.star_wide_2)
    ImageView star2;
    @BindView(R.id.star_wide_3)
    ImageView star3;
    @BindView(R.id.star_wide_4)
    ImageView star4;
    @BindView(R.id.star_compare_txt)
    TextView starDetailsTxt;

    private ActionEditContractActivityBean editActivityBean;
    private TaskActionApiIml mTaskActionApiIml;

    @BindView(R.id.error_content)
    RelativeLayout errorLayout;

    private List<CommonLabel> initKeyList;

    private Subscription requestDataSub;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBaseData();
//        initErrorBitmap();
        initBaseView();
    }

    public static void startActivity(Context mContext, String actionId) {
        IntentUtils.startActivityWithString(ActionBaseBean.ACTION_ID_KEY, actionId, mContext, ActionExamineActivity.class);
    }

    private void requestData() {
        getFromRequest();
    }

    private void initBaseView() {
        initErrorLayout();
        labels = new TextView[]{label1, label2, label3, label4, label5, label6};
        ImageView[] wideStars = new ImageView[]{star0, star1, star2, star3, star4};
        for (int index = 0; index < wideStars.length; index++)
            wideStars[index].setOnClickListener(new StartSelectedOnClickListener(index, wideStars));
        recyclerProImg.post(new Runnable() {
            @Override
            public void run() {
                initRecyclerView();
                requestData();
            }
        });
    }

    private void initRecyclerView() {
        //过程分析数据
        analysisAdapter = new ActionImageBrightPointProcessAdapterHolder(this, analysisList);
        analysisRecy.setNestedScrollingEnabled(false);
        analysisRecy.setHasFixedSize(true);
        analysisRecy.setLayoutManager(new LinearLayoutManager(this));
        analysisRecy.setItemAnimator(new DefaultItemAnimator());
        analysisRecy.setAdapter(analysisAdapter);
        //图片选择的横向的recyclerView
        imageContentAdapter = new ActionBrightPointImageAdapterHolder(this, processImg, recyclerProImg.getWidth());
        recyclerProImg.setHasFixedSize(true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerProImg.setLayoutManager(layoutManager);
        recyclerProImg.setItemAnimator(new DefaultItemAnimator());
        recyclerProImg.setAdapter(imageContentAdapter);
        imageContentAdapter.setOnItemClickListener(this);
        //图片描述的纵向RecyclerView
        detailsAdapter = new ActionImageBrightPointProcessAdapterHolder(this, processStr);
        recyclerProTxt.setNestedScrollingEnabled(false);
        recyclerProTxt.setHasFixedSize(true);
        recyclerProTxt.setLayoutManager(new LinearLayoutManager(this));
        recyclerProTxt.setItemAnimator(new DefaultItemAnimator());
        recyclerProTxt.setAdapter(detailsAdapter);
    }

    private void initEditPager() {
        editPager.getLayoutParams().height = editPager.getWidth();
        targetAdapter = new EditContractPagerAdapter(this, mergeImageList);
        editPager.setAdapter(targetAdapter);
//        editPager.setScrollBarFadeDuration(1000);
//        initIndicator();
        magicIndicator.setViewPager(editPager);
        magicIndicator.setPadding(5, 5, 10, 15);
    }

    private void initBaseData() {
        mergeImageList = new ArrayList<>();
        analysisList = new ArrayList<>();
        processStr = new ArrayList<>();
        processImg = new ArrayList<>();
        imageDetails = new ActionSelectedProcessImageDetails();
        Bundle bundle = getIntent().getExtras();
        if (mTaskActionApiIml == null) {
            mTaskActionApiIml = TaskActionApiIml.getInstance();
        }
        if (bundle != null)
            actionId = bundle.getString(ActionBaseBean.ACTION_ID_KEY);
//         actionId = VIRTUAL_ID;
    }

    private void initErrorLayout() {
        errorLayout.setVisibility(View.VISIBLE);
        errorLayout.removeAllViews();
        errorLayout.addView(ErrorViewCreateUtils.createLoadingView(this));
    }

    private void getFromRequest() {
        requestDataSub = ActionManageApiStoreIml.getInstance().getActionBrightPointMsg(actionId).subscribe(new Observer<ActionEditContractActivityBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                NaizhuAILog.e(TAG + "_e=" + e.getMessage());
                ApiException.showException(e, getActivityContext());
                errorLayout.removeAllViews();
                errorLayout.addView(ErrorViewCreateUtils.createNoNetworkView(getActivityContext(), v -> {
                    initErrorLayout();
                    requestData();
                }));
            }

            @Override
            public void onNext(ActionEditContractActivityBean actionEditContractActivityBean) {
                if (actionEditContractActivityBean != null) {
                    errorLayout.removeAllViews();
                    errorLayout.setVisibility(View.INVISIBLE);
                    editActivityBean = actionEditContractActivityBean;
                    initKeyList = actionEditContractActivityBean.getInitLabelModule();
                    refreshData();
                } else {
                    shortToast(getText(R.string.get_data_fail).toString());
                }
            }
        });
    }

    @Override
    public void onBackPressedWithoutDialog() {
        if (requestDataSub != null && !requestDataSub.isUnsubscribed()) {
            requestDataSub.unsubscribe();
        }
        super.onBackPressedWithoutDialog();
    }

    //更新数据
    private void refreshData() {
        createTxtData();
        changeImageData();
    }

    private void changeImageData() {
        List<SimpleKeyValueBean> showImage = new ArrayList<>();
        for (String img : processImg) {
            showImage.add(new SimpleKeyValueBean(ActionAddImageAdapterHolder.URL_NET_IMAGE, img));
        }
        imageDetails.setImageList(showImage);
    }

    private void createTxtData() {
        //更新题目
        actionName.setText(editActivityBean.getQuestionTitle());
        //更新合成图片
        mergeImageList.clear();
        mergeImageList.addAll(editActivityBean.getCompareImage());
        initEditPager();
        //分析
        analysisList.clear();
        analysisList.addAll(ListUtils.removeEmpty(editActivityBean.getThinkingDetail()));
        analysisAdapter.notifyDataSetChanged();
        if (analysisList.size() > 0) {
            analysisLayout.setVisibility(View.VISIBLE);
        } else
            analysisLayout.setVisibility(View.GONE);
        //过程数据
        processStr.clear();
        processStr.addAll(ListUtils.removeEmpty(editActivityBean.getProcessDetail()));
        detailsAdapter.notifyDataSetChanged();
        processImg.clear();
        processImg.addAll(editActivityBean.getProcessImages());
        imageContentAdapter.notifyDataSetChanged();
        if (processStr.size() > 0 || processStr.size() > 0)
            processLayout.setVisibility(View.VISIBLE);
        else
            processLayout.setVisibility(View.GONE);
        //心得
        if (!TextUtils.isEmpty(editActivityBean.getReview()))
            actionExperience.setText(editActivityBean.getReview());
        else
            experienceCard.setVisibility(View.GONE);
        //標簽選擇
        initLabelClassifyData(editActivityBean.getChosenLabels());

        //行为行动分数
        String score = editActivityBean.getActionScore();
        if (TextUtils.isEmpty(editActivityBean.getActionScore()))
            score = "0";
        actionPoint.setText(String.format(getText(R.string.action_point_value).toString(), score));

        //数据结构体
        if (editActivityBean.getSelectedCompareData() != null && editActivityBean.getSelectedCompareData().size() > 0 && !TextUtils.isEmpty(editActivityBean.getSelectedCompareData().get(0).getPointId())) {
            ActionCompareDataBean compareDataBean = editActivityBean.getSelectedCompareData().get(0);
            //金額的占位String
            String valueNumber = getString(R.string.action_compare_data);
            String radiuNumber = getString(R.string.improve_ratio_data);
            String moneyNumber = getString(R.string.improve_money_data);
            String pre = compareDataBean.getbValue();
            String after = compareDataBean.getaValue();
            String afterValue = String.format(valueNumber, after, compareDataBean.getUnit());
            aftData.setText(afterValue);
            String preValue = String.format(valueNumber, pre, compareDataBean.getUnit());
            preData.setText(preValue);
            String ratio = MathUtils.numberRadius(pre, after);
            if (ratio != null) {
                proRatio.setText(String.format(radiuNumber, ratio, getString(R.string.percent)));
            } else
                proRatio.setText(getText(R.string.error_data));
            proMoney.setText(String.format(moneyNumber, compareDataBean.getSimulatedAmount()));

            if (!TextUtils.isEmpty(compareDataBean.getbFormula())) {
                bValueLayout.setVisibility(View.VISIBLE);
                beforeValueType.setText(compareDataBean.getbFormula());
            } else
                bValueLayout.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(compareDataBean.getaFormula())) {
                aValueLayout.setVisibility(View.VISIBLE);
                afterValueType.setText(compareDataBean.getaFormula());
            } else
                aValueLayout.setVisibility(View.GONE);
        } else
            compareDataCard.setVisibility(View.GONE);

    }

    private void setLabelsAllEnable(TextView[] labelsView, boolean enable) {
        for (TextView text : labelsView) {
            text.setEnabled(enable);
        }
    }

    private void setLabelsEnable(TextView[] labelsView, int position, boolean enable) {
        labelsView[position].setEnabled(enable);
    }

    private void setLabelsAllSelected(TextView[] labelsView, boolean enable) {
        for (TextView text : labelsView) {
            text.setSelected(enable);
        }
    }

    private void setLabelsSelected(TextView[] labelsView, int position, boolean enable) {
        labelsView[position].setSelected(enable);
    }


    private void setLabelsViewText(List<CommonLabel> labels, TextView[] labelsView) {
        labelsRoot_5 = labels.get(3).key;
        for (int index = 0; index < labels.size(); index++) {
            labelsView[index].setText(labels.get(index).getPickerViewText());
        }
    }

    class LabelsTextOnClickListener implements View.OnClickListener {
        private int position;
        private TextView[] labelsView;

        public LabelsTextOnClickListener(int position, TextView[] labelsView) {
            this.position = position;
            this.labelsView = labelsView;
        }

        @Override
        public void onClick(View v) {
            String rootId;
            if (position != 4)
                rootId = initKeyList.get(position).key;
            else
                rootId = labelsRoot_5;
            mTaskActionApiIml.sub_label_list(rootId)
                    .subscribe(new Observer<List<CommonLabel>>() {

                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            NaizhuAILog.e("onError(Throwable e)=" + e.getMessage());
                        }

                        @Override
                        public void onNext(List<CommonLabel> result) {
                            NaizhuAILog.e("size=" + MathUtils.getCyclerSize(result, 0));
                            initOptionsLabel(result, position, MathUtils.getCyclerSize(result, 0))
                                    .subscribe(new Action1<CommonLabel>() {
                                        @Override
                                        public void call(CommonLabel labels) {
                                            selectorLabel.set(position, labels);
                                            labelsView[position].setText(labels.getPickerViewText());
                                            labelsView[position].setSelected(true);
                                            if (labelsView.length > position + 1) {
                                                if (!labelsView[position + 1].isEnabled())
                                                    labelsView[position + 1].setEnabled(true);
                                                if (position == 3 && labelsView[4].isEnabled()) {
                                                    labelsRoot_5 = labels.key;
                                                    labelsView[4].setSelected(false);
                                                    selectorLabel.set(position + 1, null);
                                                    labelsView[4].setText(getString(R.string.label_unknown));
                                                }
                                            }
                                        }
                                    });
                        }
                    });
        }
    }

    private void initLabelClassifyData(List<CommonLabel> module) {
        if (module == null || module.size() != 6) {
            if (initKeyList == null || initKeyList.size() != 6) {
                return;
            }
            module = initKeyList;
        }
        selectorLabel = module;
        setLabelsAllSelected(labels, false);
        setLabelsViewText(module, labels);
//        setLabelsAllEnable(labels, false);
//        setLabelsEnable(labels, 0, true);
        for (int position = 0; position < labels.length; position++)
            labels[position].setOnClickListener(new LabelsTextOnClickListener(position, labels));
    }

    @OnClick({R.id.submit_action, R.id.back_icon})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.submit_action:
                submitActionPoint();
                break;
            case R.id.back_icon:
                onBackPressed();
                break;
        }
    }

    private void submitActionPoint() {
        Map<String, String> subMit = new HashMap<>();
        NaizhuAILog.e("actionId=" + actionId);
        subMit.put(SubmitExamineBean.QUESTION_ID_KEY, actionId);
        subMit.put(SubmitExamineBean.SCORE_KEY, String.valueOf(selectPoint));

        if (selectorLabel.contains(null)) {
            DialogUtils.showPromptDialog(this, getString(R.string.label_unfinished));
            return;
        }
        subMit.put(SubmitExamineBean.DESC_LABELS_KEY, new Gson().toJson(selectorLabel));
        NaizhuAILog.e("DESC_LABELS_KEY=" + new Gson().toJson(selectorLabel));
        showWaitDiaLog();
        ActionManageApiStoreIml.getInstance().submitExamineDetails(subMit).subscribe(new Observer<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                hideWaitDialog();
                ApiException.showException(e, getActivityContext(), true);
                NaizhuAILog.e("submit_Throwable=" + e.getMessage());
            }

            @Override
            public void onNext(String s) {
                hideWaitDialog();
                if (ConstantsState.isResultOk(s)) {
                    shortToast(getString(R.string.submit_ok));
                    finish();
                } else
                    shortToast(getString(R.string.submit_fail));
            }
        });
    }

    private PublishSubject<CommonLabel> initOptionsLabel(List<CommonLabel> result, int position, int size) {
        PublishSubject<CommonLabel> subject = PublishSubject.create();
        List<CommonLabel> options1Items = new ArrayList<>();
        List<List<CommonLabel>> options2Items = new ArrayList<>();

        List<List<List<CommonLabel>>> options3Items = new ArrayList<>();
        for (CommonLabel label : result) {
            options1Items.add(label);
            ArrayList<CommonLabel> temp = new ArrayList<>();
            List<List<CommonLabel>> temp2 = new ArrayList<>();
            if (label.msubList.size() > 0) {
                temp.addAll(label.msubList);
            } else {
                if (size > 1)
                    temp.addAll(Collections.singletonList(label));
                if (size > 2)
                    temp2.addAll(Collections.singletonList(Collections.singletonList(label)));
            }
            for (CommonLabel labelChild : label.msubList) {
                ArrayList<CommonLabel> temp3 = new ArrayList<>();
                if (labelChild.msubList.size() > 0) {
                    temp3.addAll(labelChild.msubList);
                } else {
                    if (size > 2)
                        temp3.addAll(Collections.singletonList(labelChild));
                }
                temp2.add(temp3);
            }
            options2Items.add(temp);
            options3Items.add(temp2);
        }
        OptionsPickerView<CommonLabel> pvLabelOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                CommonLabel key = null;
                switch (size) {
                    case 1:
                        key = options1Items.get(options1);
                        break;
                    case 2:
                        key = options2Items.get(options1).get(options2);
                        break;
                    case 3:
                        key = options3Items.get(options1).get(options2).get(options3);
                        break;
                }
                subject.onNext(key);
            }
        })
                .setTitleText(getString(R.string.label_selector))
                .setCancelColor(Color.GRAY)
                .setSubmitColor(getResources().getColor(R.color.lightorange))
                .setTextColorCenter(Color.LTGRAY)
                .build();
        switch (size) {
            case 1:
                pvLabelOptions.setPicker(options1Items);
                break;
            case 2:
                pvLabelOptions.setPicker(options1Items, options2Items);
                break;
            case 3:
                pvLabelOptions.setPicker(options1Items, options2Items, options3Items);
                break;
        }
        pvLabelOptions.show();
        return subject;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_business_action_examine_layout;
    }

    @Override
    public void onItemClick(View view, int position) {
        imageDetails.setPosition(position);
        imageDetails.setEdit(false);
        IntentUtils.startActivityWithObject(ActionShowChoseImageActivity.IMAGE_DATA_DETAILS, imageDetails, this, ActionShowChoseImageActivity.class);
    }

    class StartSelectedOnClickListener implements View.OnClickListener {

        private int position;
        private ImageView[] starImage;

        public StartSelectedOnClickListener(int position, ImageView[] starImage) {
            this.position = position;
            this.starImage = starImage;
        }

        @Override
        public void onClick(View v) {
            selectPoint = position + 1;
            for (int index = 0; index < starImage.length; index++) {
                if (index < position + 1)
                    starImage[index].setImageResource(R.mipmap.star_good_wide);
                else
                    starImage[index].setImageResource(R.mipmap.star_bad_wide);
            }
        }
    }


    //轮播图适配器
    private class EditContractPagerAdapter extends PagerAdapter {
        private BaseActivity mContext;
        private List<CompareImageBean> editImage;

        EditContractPagerAdapter(BaseActivity context, List<CompareImageBean> editImage) {
            this.mContext = context;
            this.editImage = editImage;
        }

        @Override
        public int getCount() {
            return editImage.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            ImageView item = new ImageView(mContext);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            item.setLayoutParams(params);
            ImageUtils.glideImageViewByUrl(mContext, item, editImage.get(position).getMergeImageUrl());
            container.addView(item);
            return item;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup collection, int position, @NonNull Object view) {
            collection.removeView((View) view);
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    }
}
